package cn.xing.managementSystem.service;

import cn.xing.managementSystem.domain.ImageStore;
import cn.xing.managementSystem.domain.RollingImage;
import cn.xing.managementSystem.repository.base.RollingImageRepository;
import cn.xing.managementSystem.utils.Preconditions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * @author cuixing
 * @package cn.xing.managementSystem.service
 * @class RollingImageService
 * @email xing.cui@magicwindow.cn
 * @date 2018/4/24 下午11:36
 * @description
 */
@Service
@Transactional
public class RollingImageService {


    @Autowired
    private RollingImageRepository rollingImageRepository;

    @Autowired
    private ImageStoreService imageStoreService;

    @Value("${image.boot.path}")
    private String imageBootPath;

    public List<RollingImage> getRollingImageList(){
        return rollingImageRepository.findAll();
    }

    public RollingImage findById(Long id){
        return rollingImageRepository.findByIdAndAndDeletedIsFalse(id);
    }

    public boolean saveRollingImages(String [] rollingImageIds, String [] imageStoreIds, List<MultipartFile> files) throws IOException {
        for(int i = 0; i < rollingImageIds.length; i++){
            RollingImage rollingImage = this.findById(Long.valueOf(rollingImageIds[i]));
            if(Preconditions.isBlank(imageStoreIds[i])){
                if(Preconditions.isNotBlank(files.get(i).getOriginalFilename())){
                    MultipartFile file = files.get(i);
                    ImageStore imageStore = imageStoreService.saveImageStore(file);
                    rollingImage.setImageStore(imageStore);
                }else {
                    rollingImage.setImageStore(null);
                }
                rollingImage = rollingImageRepository.saveAndFlush(rollingImage);
                if(Preconditions.isBlank(rollingImage)){
                    return false;
                }
            }
        }
        return true;
    }
}